package com.aaa.sso.service;

import com.aaa.common.entity.Users;
import com.aaa.sso.dao.UsersMapper;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * fileName:UserServiceImpl
 * description:
 * author:zz
 * createTime:2020/8/29 15:23
 * version:1.0.0
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public String checkUserInfo(String userName, String passWord) {
        //验证用户名和密码是否正确
        Users userInfo = usersMapper.getUserByParam(userName, passWord);
        //如果用户信息为空，说明用户名错误，直接返回登录错误
        if(userInfo==null){
            return "loginFail";
        }
        //获取盐值
        String passwordSalt = userInfo.getPasswordSalt();
        //使用用户添加时使用的密码加密算法，再次计算密码   Sha512Hash("tiger ","2238b20d-84a1-4",1024);
        Sha512Hash sha512Hash = new Sha512Hash(passWord,passwordSalt,1024);
        //密码正确,认证成功
        if(sha512Hash.toString().equals(userInfo.getPassword())){
            //生成token
              String accessToken  = userName+System.currentTimeMillis();
             // String accessToken  =   userName+UUID.randomUUID().toString().substring(0,15);
             // 存入redis  key+value     key = caidong+1598689318119    value = userInfo
              redisTemplate.opsForValue().set(accessToken,userInfo,60, TimeUnit.MINUTES);
              return accessToken;
        }
        //正确时，生成token值，返回，并保存redis集群中
        return "loginFail";
    }

    @Override
    public boolean checkToken(String accessToken) {
        //验证token是否正确
       return  redisTemplate.hasKey(accessToken);
    }

   /* public static void main(String[] args) {
        String salt = UUID.randomUUID().toString().substring(0,15);
        System.out.println("随机盐值："+salt);
        Sha512Hash sha512Hash = new Sha512Hash("tiger",salt,1024);
        System.out.println(sha512Hash.toString());
        System.out.println(System.currentTimeMillis());
    }*/

    @Override
    public Users getUserInfoByToken(String accessToken) {
        Users users = (Users)redisTemplate.opsForValue().get(accessToken);
       // System.out.println(users.getUsername()+".........是否可以获取...........");
        return users;
    }

    @Override
    public String userLogOut(String accessToken) {
        Boolean isSuc = redisTemplate.delete(accessToken);
        if(isSuc){
            return "noLogin";
        }
        return "logOutFail";
    }
}
